package com.example.demo.stream.parallel;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author MarioZzz
 * @create 2023-10-24 16:29
 */
public class ParallelStreamTest {

    private static final int COUNT = 1000;

    public static void main(String[] args) {
        List<RiderDto> oriList = new ArrayList<>();
        //开始时间
        long startTime = System.currentTimeMillis();

        //初始化数据
        for (int i = 0; i < COUNT; i++) {
            oriList.add(init());
        }
        long endTime1 = System.currentTimeMillis();

        final List<RiderDto> copyList = new ArrayList<>();
        oriList.parallelStream().forEach(rider -> {
            copyList.add(twins(rider));
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime2 = System.currentTimeMillis();

        final List<RiderDto> simpleCopyList = new ArrayList<>();
        oriList.forEach(rider -> {
            simpleCopyList.add(twins(rider));
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime3 = System.currentTimeMillis();

        System.out.println("oriList size:" + oriList.size() + " ,time:" + (endTime1 - startTime) + "ms");
        System.out.println("copyList size:" + copyList.size() + " ,time:" + (endTime2 - endTime1) + "ms");
        System.out.println("simpleCopyList size:" + simpleCopyList.size() + " ,time:" + (endTime3 - endTime2) + "ms");
    }

    private static RiderDto twins(RiderDto rider) {
        //对数据做些操作，实际业务会比这复杂
        RiderDto t = new RiderDto();
        t.setId(rider.getId());
        t.setCityId(rider.getCityId());
        return t;
    }

    private static RiderDto init() {
        RiderDto t = new RiderDto();
        Random random = new Random();
        t.setId(random.nextInt(2 ^ 20));
        t.setCityId(random.nextInt(1000));
        return t;
    }

    @Data
    static class RiderDto implements Serializable {
        private static final long serialVersionUID = 1;
        private Integer cityId;
        private Integer id;
    }

}
